import pyautogui
import time
import sys
import os
import pygetwindow
import pygetwindow as gw
import ctypes
import win32gui
import win32con
import numpy as np
import cv2
import pytesseract
import pydirectinput
from PIL import ImageGrab,Image
from utils import getpngfromShot
def sleep(t):
    time.sleep(t)

x = 0;
y = 0;
xing = 0;
def make_window_active(window_title):
    try:
        # 获取当前活动窗口的句柄
        foreground_window = win32gui.GetForegroundWindow()

        # 获取目标窗口
        windows = gw.getWindowsWithTitle(window_title)
        if not windows:
            print(f"No windows found with title '{window_title}'.")
            return False
        
        target_window = windows[0]._hWnd  # 获取第一个匹配窗口的句柄
        
        # 判断目标窗口是否为当前活动窗口
        if foreground_window == target_window:
            print(f"Window '{window_title}' is already the active window.")
            return True
        
        # 将窗口设置为活动窗口
        win32gui.ShowWindow(target_window, win32con.SW_RESTORE)  # 恢复窗口（如果它被最小化）
        win32gui.SetForegroundWindow(target_window)  # 设置为前景窗口
        
        print(f"Window '{window_title}' has been set as the active window.")
        return True
    except Exception as e:
        print(f"Error: {e}")
        return False
def init():
    #make_window_active('崩坏：星穹铁道')
    global x,y,xing
    # 获取指定标题的程序窗口对象
    xings = pygetwindow.getWindowsWithTitle('绝区零')[0]
    # xings = pygetwindow.getWindowsWithTitle('星穹铁道')[0]
    # xings = pygetwindow.getWindowsWithTitle('原神')[0]
    # xings = pygetwindow.getWindowsWithTitle('雷电模拟器')[0]
    xing = xings
    # 获取窗口左上角的位置
    top_left_position = xings.topleft
    x = top_left_position.x
    y = top_left_position.y
def getpng():
    region = (759,557,860,604)
    screenshot = ImageGrab.grab(bbox=region)
    save_path = "zzz/六分街2.png"
    if os.path.exists(save_path):
        print("文件已存在！！！")
        return 
    screenshot.save(save_path)
    screenshot.show()
def checkpng():
    print("=======check_png=========")
    small = Image.open("zzz/自定义模版.png")
    # small = Image.open("xing/今宵之形.png")
    # small = Image.open("yuan/褪色的剧场.png")
    # small = Image.open("miyoushe/青少年模式.png")
    # small.show()
    big = pyautogui.screenshot(region=[x,y,xing.width,xing.height])
    # big.show()
    point = getpngfromShot(small,big,0.9,True)
    print("png point = ",point)
    return point
def getSP():
    # region = (x+1370,y+77,x+1410,y+104)
    region = (x+1233,y+82,x+1269,y+102)
    screenshot = ImageGrab.grab(bbox=region)
    screenshot.save("xing\sp.png")
    screenshot.show()
    image = np.asarray(screenshot)
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    _,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    custom_config = r'--oem 3 --psm 6 outputbase digits'
    text = pytesseract.image_to_string(thresh,config=custom_config)
    print(type(text))
    for t in text:
        print(t)
    print(text.strip().isdigit())
    if text == "":
        print("text = null")
    else:
        print("text =",text)



# main
if __name__ == "__main__":
    sleep(2)
    init()
    print(x,y,xing)
    sleep(1)

    # getpng()
    # sleep(2)
    checkpng()
    # getSP()
